package com.bigdata.demo.service.letter;

import com.bigdata.demo.entity.CRReport;
import com.bigdata.demo.entity.ECMLetter;
import com.bigdata.demo.repository.CRReportRepository;
import com.bigdata.demo.repository.ECMLetterRepository;
import com.bigdata.demo.service.ServiceMultiResult;
import com.bigdata.demo.service.ServiceResult;
import com.bigdata.demo.service.search.*;
import com.bigdata.demo.web.dto.CRDTO;
import com.bigdata.demo.web.dto.ECMLetterDTO;
import com.bigdata.demo.web.form.CRReportSearch;
import com.bigdata.demo.web.form.ECMLetterSearch;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import org.elasticsearch.action.admin.indices.analyze.AnalyzeAction;
import org.elasticsearch.action.admin.indices.analyze.AnalyzeRequestBuilder;
import org.elasticsearch.action.admin.indices.analyze.AnalyzeResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.index.reindex.DeleteByQueryRequestBuilder;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SearchDocServiceImpl implements ISearchDocService {

    private static final Logger logger = LoggerFactory.getLogger(ISearchDocService.class);
    private static final String INDEX_NAME = "ecm";

    private static final String INDEX_TYPE = "letter";

    @Autowired
    private TransportClient esClient;

    @Autowired
    private ECMLetterRepository ecmLetterRepository;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ModelMapper modelMapper;


    public void createOrUpdateIndex(DocIndexMessage message) {
        Integer id=message.getId();
        ECMLetter ecmLetter = ecmLetterRepository.findById(id).get() ;

        if (ecmLetter == null) {
            logger.error("Index id_key_cr {} dose not exist!", id);
            this.index(id, message.getRetry() + 1);
            return;
        }

        DocIndexTemplate indexTemplate = new DocIndexTemplate();
        modelMapper.map(ecmLetter, indexTemplate);
        indexTemplate.setId(id);

        SearchRequestBuilder requestBuilder = this.esClient.prepareSearch(INDEX_NAME).setTypes(INDEX_TYPE)
                .setQuery(QueryBuilders.termQuery(DocIndexKey.ID, id));

        logger.debug(requestBuilder.toString());
        SearchResponse searchResponse = requestBuilder.get();

        boolean success;
        long totalHit = searchResponse.getHits().getTotalHits();
        if (totalHit == 0) {
            success = create(indexTemplate);
        } else if (totalHit == 1) {
            String esId = searchResponse.getHits().getAt(0).getId();
            success = update(esId, indexTemplate);
        } else {
            success = deleteAndCreate(totalHit, indexTemplate);
        }


        if(!success)
            logger.error("Error when Update index with cr: " + indexTemplate.getId());


    }



    private boolean deleteAndCreate(long totalHit, DocIndexTemplate indexTemplate) {
        DeleteByQueryRequestBuilder builder = DeleteByQueryAction.INSTANCE
                .newRequestBuilder(esClient)
                .filter(QueryBuilders.termQuery(DocIndexKey.ID, indexTemplate.getId()))
                .source(INDEX_NAME);

        logger.debug("Delete by query for doc: " + builder);

        BulkByScrollResponse response = builder.get();
        long deleted = response.getDeleted();
        if (deleted != totalHit) {
            logger.warn("Need delete {}, but {} was deleted!", totalHit, deleted);
            return false;
        } else {
            return create(indexTemplate);
        }
    }

    private boolean update(String esId, DocIndexTemplate indexTemplate) {
        if (!updateSuggest(indexTemplate)) {
            return false;
        }

        try {
            UpdateResponse response = this.esClient.prepareUpdate(INDEX_NAME, INDEX_TYPE, esId).setDoc(objectMapper.writeValueAsBytes(indexTemplate), XContentType.JSON).get();

            logger.debug("Update index with doc: " + indexTemplate.getId());
            if (response.status() == RestStatus.OK) {
                return true;
            } else {
                return false;
            }
        } catch (JsonProcessingException e) {
            logger.error("Error to index cr " + indexTemplate.getId(), e);
            return false;
        }
    }

    private boolean create(DocIndexTemplate indexTemplate) {
        if (!updateSuggest(indexTemplate)) {
            return false;
        }

        try {
            IndexResponse response = this.esClient.prepareIndex(INDEX_NAME, INDEX_TYPE)
                    .setSource(objectMapper.writeValueAsBytes(indexTemplate), XContentType.JSON).get();

            logger.debug("Create index with doc: " + indexTemplate.getId());
            if (response.status() == RestStatus.CREATED) {
                return true;
            } else {
                return false;
            }
        } catch (JsonProcessingException e) {
            logger.error("Error to index doc " + indexTemplate.getId(), e);
            return false;
        }
    }
    private boolean updateSuggest(DocIndexTemplate indexTemplate) {
        AnalyzeRequestBuilder requestBuilder = new AnalyzeRequestBuilder(
                this.esClient, AnalyzeAction.INSTANCE, INDEX_NAME, indexTemplate.getDocumenttitle(),
                indexTemplate.getDocumentnumber());

        requestBuilder.setAnalyzer("ik_smart");

        AnalyzeResponse response = requestBuilder.get();
        List<AnalyzeResponse.AnalyzeToken> tokens = response.getTokens();
        if (tokens == null) {
            logger.warn("Can not analyze token for doc: " + indexTemplate.getId());
            return false;
        }

        List<DocSuggest> suggests = new ArrayList<>();
        for (AnalyzeResponse.AnalyzeToken token : tokens) {
            // 排序数字类型 & 小于2个字符的分词结果
            if ("<NUM>".equals(token.getType()) || token.getTerm().length() < 2) {
                continue;
            }

            DocSuggest suggest = new DocSuggest();
                    suggest.setInput(token.getTerm());
                    suggests.add(suggest);

        }
        DocSuggest suggest = new DocSuggest();
        suggest.setInput(indexTemplate.getDocumenttitle());
        suggests.add(suggest);
        suggest = new DocSuggest();
        suggest.setInput(indexTemplate.getDocumentnumber());
        suggests.add(suggest);
            indexTemplate.setSuggest(suggests);
            return true;

    }


    private void index(int id, int retry) {
        if (retry > DocIndexMessage.MAX_RETRY) {
            logger.error("Retry index times over 3 for cr: " + id + " Please check it!");
            return;
        }

        DocIndexMessage message = new DocIndexMessage(id, DocIndexMessage.INDEX, retry);
        try {
            this.createOrUpdateIndex(message);
        } catch ( Exception e) {
            logger.error("Json encode error for " + message);
        }

    }



    @Override
    public ServiceMultiResult<ECMLetterDTO> query(ECMLetterSearch ecmLetterSearch) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if(ecmLetterSearch.getKeyword()==null){
            ecmLetterSearch.setKeyword("");
        }
        List<ECMLetterDTO> list=new ArrayList<>();
        boolQuery.must(
                QueryBuilders.multiMatchQuery(ecmLetterSearch.getKeyword(),
                        DocIndexKey.DOCTITLE,DocIndexKey.DOCNUMBER
                ));

        SearchRequestBuilder requestBuilder = this.esClient.prepareSearch(INDEX_NAME)
                .setTypes(INDEX_TYPE)
                .setQuery(boolQuery)
                .addSort(
                        "_score",
                        SortOrder.fromString("desc")
                )
                .setFrom(ecmLetterSearch.getStart())
                .setSize(ecmLetterSearch.getSize())
                .setFetchSource(DocIndexKey.ID, null);

        List<Integer> ids = new ArrayList<>();
        SearchResponse response = requestBuilder.get();
        if (response.status() != RestStatus.OK) {
            logger.warn("Search status is no ok for " + requestBuilder);
            return new ServiceMultiResult<>(0, list);
        }

        for (SearchHit hit : response.getHits()) {
         //   System.out.println(hit.getSource());
            ids.add((Integer) hit.getSource().get(DocIndexKey.ID));
        }

        for (Integer id:ids){
         ECMLetter ecmLetter=  ecmLetterRepository.findById(id).get();
         ECMLetterDTO ecmLetterDTO=new ECMLetterDTO();
         modelMapper.map(ecmLetter,ecmLetterDTO) ;
         list.add(ecmLetterDTO);
        }

        return new ServiceMultiResult<>(list.size(), list);

    }


    @Override
    public ServiceResult<List<String>> suggest(String prefix) {
        CompletionSuggestionBuilder suggestion = SuggestBuilders.completionSuggestion("suggest").prefix(prefix).size(5);

        SuggestBuilder suggestBuilder = new SuggestBuilder();
        suggestBuilder.addSuggestion("autocomplete", suggestion);

        SearchRequestBuilder requestBuilder = this.esClient.prepareSearch(INDEX_NAME)
                .setTypes(INDEX_TYPE)
                .suggest(suggestBuilder);
        logger.debug(requestBuilder.toString());

        SearchResponse response = requestBuilder.get();
        Suggest suggest = response.getSuggest();
        if (suggest == null) {
            return ServiceResult.of(new ArrayList<>());
        }
        Suggest.Suggestion result = suggest.getSuggestion("autocomplete");

        int maxSuggest = 0;
        Set<String> suggestSet = new HashSet<>();

        for (Object term : result.getEntries()) {
            if (term instanceof CompletionSuggestion.Entry) {
                CompletionSuggestion.Entry item = (CompletionSuggestion.Entry) term;

                if (item.getOptions().isEmpty()) {
                    continue;
                }

                for (CompletionSuggestion.Entry.Option option : item.getOptions()) {
                    String tip = option.getText().string();
                    if (suggestSet.contains(tip)) {
                        continue;
                    }
                    suggestSet.add(tip);
                    maxSuggest++;
                }
            }

            if (maxSuggest > 5) {
                break;
            }
        }
        List<String> suggests = Lists.newArrayList(suggestSet.toArray(new String[]{}));
        return ServiceResult.of(suggests);
    }
}
